import { history } from 'umi';
import { login, getFakeCaptcha } from '@/services/login';
import { list } from '@/services/system/resource';
//import { setAuthority } from '@/utils/authority';
import { setToken, removeToken, setUser, setModuleList, setModuleCurrent } from '@/utils/token';

const Model = {
  namespace: 'login',
  state: {
    status: {
      success: true,
      msg: ''
    },
    captcha: {
      deviceId: null,
      content: null,
    }
  },
  effects: {
    *captchaEffects({ payload }, { call, put }) {
      const response = yield call(getFakeCaptcha);
      yield put({ type: 'captchaReducers', payload: response.data, }); 
    },
    *loginEffects({ payload }, { call, put }) {
      const response = yield call(login, payload);
      yield put({type: 'statusReducers',payload: response,});

      if (response.success) {
        setToken(response.data.accessToken);
        setUser(response.data.user);
        
        const res = yield call(list);
        const moduleList = res.data;
        setModuleList(moduleList);
        if (moduleList && moduleList.length > 0) {
          setModuleCurrent(moduleList[0]);
        }

        history.replace('/');
      } else {
        // 登录失败，重新获取验证码
        const response = yield call(getFakeCaptcha);
        yield put({ type: 'captchaReducers', payload: response.data, }); 
      }
    },

    logout() {
      removeToken();
      history.replace('/user/login');
    },
  },
  reducers: {
    statusReducers(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      return { ...state, status: payload };
    },
    captchaReducers(state, { payload }) {
      return { ...state, captcha: payload };
    }
  },
};
export default Model;
